﻿<%@ WebHandler Language="C#" Class="multiupload" %>

using System;
using System.Web;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;


public class multiupload : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        context.Response.Headers.Add("connection", "keep-alive");
        context.Response.CacheControl = "no-cache";
        context.Response.AddHeader("Connection", "Keep-Alive");
        context.Response.Headers.Set("Connection", "Keep-Alive");
        context.Response.Headers.Add("Connection", "Keep-Alive");
        context.Response.AppendHeader("Connection", "Keep-Alive");
        string detailid = HttpContext.Current.Request.Params["batch_id"];
        string batch_number = HttpContext.Current.Request.Params["batch_number"];
        SaveFile(detailid,batch_number);  
    }
    
    MsSqlHelper mssql = new MsSqlHelper();
    Common Init = new Common();

    /// <summary>
    /// 文件保存操作
    /// </summary>
    /// <param name="basePath"></param>
    private void SaveFile(string detailid,string batch_number,string basePath = "~/Upload/Images/")
    {
        var name = string.Empty;
        string fullbasePath = (basePath.IndexOf("~") > -1) ? HttpContext.Current.Server.MapPath(basePath) :
        fullbasePath = basePath;
        HttpFileCollection files = HttpContext.Current.Request.Files;
        HttpPostedFile file;
        string folderdt = DateTime.Now.ToString("yyyy'/'MM'/'dd");
        if (!Directory.Exists(fullbasePath))
            Directory.CreateDirectory(fullbasePath);
        if (!Directory.Exists(basePath + folderdt + "\\"))
            Directory.CreateDirectory(fullbasePath + folderdt + "\\");
        string f = "00000000";
        for (int i = 0; i < HttpContext.Current.Request.Files.Count; ++i)
        {
            file = HttpContext.Current.Request.Files[i];
            f= Init.maxbh().ToString() ;
            string full = fullbasePath + folderdt + "\\" + f + Path.GetExtension(file.FileName);
            string sql = "insert into [ImageDoc](imageid,type_id,leibie,detailid,extend,beactive,url,fzxx1,fzxx5,lastmodifytime)values('" + f + "','bg','检验报告','" + detailid + "','" + Path.GetExtension(file.FileName) + "','是','" + basePath.Replace("~", "") + folderdt + "/" + f + Path.GetExtension(file.FileName) + "','" + batch_number + "','" + file.FileName + "',CONVERT(varchar(100), GETDATE(), 120))";
            int success = mssql.ExecuteSql(sql);
            files[0].SaveAs(full);
			try{
			 System.Drawing.Image iSource = Image.FromStream(files[0].InputStream);
			 
             string imageUrl = SaveImage(iSource, HttpContext.Current.Server.MapPath("~/Uploads/Images/"), f + Path.GetExtension(file.FileName));
			}catch (Exception ex)
        {
            Init.WriteLog(ex.ToString(), true);
        }
            var _result = "{\"code\":1,\"msg\":\"\u4e0a\u4f20\u6210\u529f"+f+"|"+file.FileName+"\"}";
            HttpContext.Current.Response.Write(_result);
        }
    }
	
	
    /// <summary>
    /// 保存图片
    /// </summary>
    /// <param name="stream">图片</param>
    /// <param name="folderName">保存路径</param>
    /// <param name="waterMark">水印文件名</param>
    /// <returns></returns>
    private string SaveImage(Image imgSource, string folderName, string waterMark)
    {
        try
        {
            //string fileName = Guid.NewGuid() + ".jpg";
			string fileName = waterMark;
            string path = "/";
            path = Path.Combine(path, folderName + "\\" + DateTime.Now.Year + "\\" + DateTime.Now.Month + "\\" + DateTime.Now.Day + "\\");
            string imageUrl = "/" + folderName + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";

            if (!string.IsNullOrEmpty(waterMark))
            {				
                ///加水印
				AddWatermarkAndSave(path, fileName, waterMark, imgSource, imgSource.Height - 300, 10, Color.Red,
                    new Font("宋体", 40));
            }            
            return imageUrl + fileName;
        }
        catch (Exception ex)
        {
            Init.WriteLog(ex.ToString(), true);
            return "";
        }
    }
	
	/// <summary>
    /// 图片加文字水印
    /// </summary>
    /// <param name="fileName"> </param>
    /// <param name="text">水印文字，如果是多行用分号隔开</param>
    /// <param name="img">图片</param>
    /// <param name="paddingTop">上边距</param>
    /// <param name="paddingLeft">左边距</param>
    /// <param name="textColor">文字颜色</param>
    /// <param name="textFont">字体</param>
    /// <param name="path">保存地址</param>
    /// <returns></returns>
    private bool AddWatermarkAndSave(string path, string fileName, string text, Image img,
                int paddingTop, int paddingLeft, Color textColor, Font textFont)
    {
        try
        {
            text = text + ";" + "当前时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            textFont = new Font("宋体", 19);

            int imgheight = img.Height;
            int imgwidth = img.Width;
            if (img.Height > 1754 && img.Width<img.Height)
            {
                imgheight = 1754;
                imgwidth =(int)((double)img.Width / ((double)img.Height / 1754.00));
            }
            if (img.Width > img.Height && img.Width > 1754)
            {
                imgwidth = 1754;
                imgheight = (int)((double)img.Height / ((double)img.Width / 1754.00));
            }
            if (img.Width > img.Height && img.Width < 1754)
            {
                imgwidth = 1754;
                imgheight = (int)((double)img.Height / ((double)img.Width / 1754.00));
            }
            if (img.Width < img.Height && img.Height < 1754)
            {
                imgheight = 1754;
                imgwidth = (int)((double)img.Width / ((double)img.Height / 1754.00)); 
            }
            if (img.Width == img.Height)
            {
                imgheight = 1240;
                imgwidth = 1240;
            }
            Bitmap Cover = new Bitmap(img, imgwidth, imgheight);
            //加载水印文件
			string sitamp="~/Public/sitamp21.png";
            string shuiyin = HttpContext.Current.Server.MapPath(sitamp);            
            System.Drawing.Image water = System.Drawing.Image.FromFile(shuiyin);
            Bitmap waters = new Bitmap(water, 300, 300);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(Cover);
            System.Drawing.Brush b = new SolidBrush(textColor);            
            g.DrawImage(waters, new Rectangle(Cover.Width - waters.Width - 80, 120, waters.Width, waters.Height), 0, 0, waters.Width, waters.Height, GraphicsUnit.Pixel);
            g.Dispose();
            Cover.Save(path + fileName, ImageFormat.Jpeg);									
            Cover.Dispose();
            return true;
        }
        catch (Exception ex)
        {
            Init.WriteLog(ex.ToString(), true);
            return false;
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}